<template>
  <n-flex v-if="content.type === 'company'" vertical align="center" :size="30" class="mt-60px">
    <n-image
      object-fit="cover"
      show-toolbar-tooltip
      preview-disabled
      width="146"
      height="146"
      style="border: 2px solid #fff"
      class="rounded-50% select-none cursor-pointer"
      :src="avatar"
      @click="openImageViewer"
      alt="" />

    <span class="text-(20px [--text-color])">{{ item.UserName }}</span>

    <span class="text-(14px #909090)">{{ item.SelfSignature || '这个人很高冷,暂时没有留下什么' }}</span>

    <span>所属公司：{{ item.CompanyName }}</span>
    <span>部门：{{ item.DepartmentName }}</span>
    <span>职位：{{ item.PositionName }}</span>
    <span>联系电话：{{ item.Mobile }}</span>
    <!-- 选项按钮 -->
    <n-flex align="center" justify="space-between" :size="60">

      <n-popover trigger="hover"
                 v-for="(item, index) in footerOptions"
                 :key="index"
      >
        <template #trigger>
          <n-button
            @click="item.click('user')"
            class="cursor-pointer"
            :border-radius="10"
            :color="'#13987f'"
          >{{ item.title }}</n-button>
        </template>
        <span>{{ item.title }}</span>
      </n-popover>
    </n-flex>
  </n-flex>

  <!-- 群聊详情 -->
  <div
    v-else-if="content.type === 'group' && item"
    class="flex flex-col flex-1 mt-60px gap-30px select-none p-[0_40px] box-border">
    <!-- 群聊头像及名称 -->
    <n-flex align="center" justify="space-between" class="px-30px box-border">
      <n-flex align="center" :size="30">
        <n-image
          object-fit="cover"
          show-toolbar-tooltip
          preview-disabled
          width="106"
          height="106"
          style="border: 2px solid #fff"
          class="rounded-50% select-none cursor-pointer"
          :src="avatar || '/logo.png'"
          @click="openImageViewer"
          alt="" />

        <n-flex vertical :size="16">
          <n-flex align="center" :size="12">
            <span class="text-(20px [--text-color])">{{ item.name }}</span>
          </n-flex>
          <n-flex align="center" :size="12">
            <span class="text-(14px #909090)">群号 {{ item.groupID }}</span>
            <n-tooltip trigger="hover">
              <template #trigger>
                <svg class="size-12px cursor-pointer color-#909090" @click="handleCopy(item.groupID)">
                  <use href="#copy"></use>
                </svg>
              </template>
              <span>复制</span>
            </n-tooltip>
          </n-flex>
        </n-flex>
      </n-flex>

      <n-flex>
        <n-icon-wrapper
          @click="footerOptions[0].click('group')"
          class="cursor-pointer"
          :size="40"
          :border-radius="10"
          :color="'#13987f'">
          <n-popover trigger="hover">
            <template #trigger>
              <n-icon :size="22">
                <svg class="color-#fff"><use href="#message"></use></svg>
              </n-icon>
            </template>
            <span>{{ footerOptions[0].title }}</span>
          </n-popover>
        </n-icon-wrapper>

        <n-icon-wrapper
          v-if="isOwner"
          @click="dismissGroup()"
          class="cursor-pointer color-warning-500"
          :size="40"
          :border-radius="10"
        >
          <n-popover trigger="hover">
            <template #trigger>
              <n-icon :size="22">
                <svg class="color-#fff"><use href="#logout"></use></svg>
              </n-icon>
            </template>
            <span>解散群聊</span>
          </n-popover>
        </n-icon-wrapper>

        <n-icon-wrapper
          v-else
          @click="quitGroup()"
          class="cursor-pointer color-warning-500"
          :size="40"
          :border-radius="10"
        >
          <n-popover trigger="hover">
            <template #trigger>
              <n-icon :size="22">
                <svg class="color-#fff"><use href="#logout"></use></svg>
              </n-icon>
            </template>
            <span>退出群聊</span>
          </n-popover>
        </n-icon-wrapper>
      </n-flex>
    </n-flex>

    <!-- 群信息列表 -->
    <n-flex vertical class="select-none w-full px-30px box-border">
      <n-flex
        align="center"
        justify="space-between"
        :class="{ 'pr-4px': item.selfInfo.nameCard }"
        class="py-6px border-b h-26px text-(14px [--chat-text-color])">
        <span>我的本群昵称</span>
        <div v-if="isEditingNickname" class="flex items-center">
          <n-input
            ref="nicknameInputRef"
            v-model:value="nicknameValue"
            size="tiny"
            class="border-(1px solid #90909080)"
            placeholder="请输入本群昵称"
            clearable
            autoComplete="off"
            autoCorrect="off"
            @blur="handleNicknameUpdate"
            @keydown.enter="handleNicknameUpdate" />
        </div>
        <span v-else class="flex items-center cursor-pointer" @click="startEditNickname">
          <span class="text-#909090">{{ item.selfInfo.nameCard || '未设置' }}</span>
          <n-icon v-if="!item.selfInfo.nameCard" size="16" class="ml-1">
            <svg><use href="#right"></use></svg>
          </n-icon>
        </span>
      </n-flex>

      <n-flex
        v-if="isOwner"
        align="center"
        justify="space-between"
        class="py-12px border-b text-(14px [--chat-text-color])">
        <span>群公告</span>
        <span class="flex items-center cursor-pointer">
          <span class="text-#909090">未设置</span>
          <n-icon size="16" class="ml-1">
            <svg><use href="#right"></use></svg>
          </n-icon>
        </span>
      </n-flex>
    </n-flex>

    <!-- 群成员 -->
    <n-flex vertical class="px-30px box-border">
      <n-flex
        v-if="!isSearch"
        align="center"
        justify="space-between"
        class="h-42px text-(14px [&#45;&#45;chat-text-color])">
        <span class="text-14px"> 群成员&nbsp; ({{ item.memberCount }}) </span>
        <svg @click="handleSelect" class="size-14px">
          <use href="#search" title="搜索"></use>
        </svg>
      </n-flex>
      <!-- 搜索框 -->
      <n-flex v-else align="center" class="h-42px">
        <n-input
          :on-input="handleSearch"
          @blur="handleBlur"
          ref="inputInstRef"
          v-model:value="searchRef"
          clearable
          placeholder="搜索"
          type="text"
          size="tiny"
          autoComplete="off"
          autoCorrect="off"
          class="h-26px w-95% lh-26px rounded-6px">
          <template #prefix>
            <svg class="w-12px h-12px">
              <use href="#search"></use>
            </svg>
          </template>
        </n-input>
      </n-flex>
      <n-flex class="item-box">
        <n-virtual-list
          id="image-chat-detail"
          style="max-height: 300px"
          item-resizable
          @scroll="handleScroll($event)"
          :item-size="36"
          :items="filteredUserList">
          <template #default="{ item }">
            <n-popover
              :ref="(el) => (infoPopoverRefs[item.userID] = el)"
              @update:show="handlePopoverUpdate(item.userID, $event)"
              trigger="click"
              placement="left"
              :show-arrow="false"
              style="padding: 0; background: var(--bg-info)">
              <template #trigger>
                <ContextMenu
                  :content="item"
                  @select="$event.click(item, 'Sidebar')"
                  :menu="optionsList"
                  :special-menu="report">
                  <n-flex
                    @click="selectKey = item.userID"
                    :key="item.userID"
                    :size="10"
                    align="center"
                    justify="space-between"
                    class="item">
                    <n-flex align="center" :size="8" class="flex-1 truncate">
                      <div class="relative inline-flex items-center justify-center">
                        <n-avatar
                          round
                          class="grayscale"
                          :class="{ 'grayscale-0': item.isOnline }"
                          :size="26"
                          :src="item.avatar"
                          fallback-src="/logo.png" />
                      </div>
                      <n-flex vertical :size="2" class="flex-1 truncate">
                        <p :title="getCompanyAndDepartment(item)" class="text-12px truncate flex-1">
                          {{ getCompanyAndDepartment(item) }}
                        </p>
                      </n-flex>
                    </n-flex>

                    <div
                      v-if="item.role === TencentCloudChat.TYPES.GRP_MBR_ROLE_OWNER"
                      class="flex px-4px bg-#d5304f30 py-3px rounded-4px size-fit select-none">
                      <p class="text-(10px #d5304f)">群主</p>
                    </div>
                    <div
                      v-if="item.role === TencentCloudChat.TYPES.GRP_MBR_ROLE_ADMIN"
                      class="flex px-4px bg-#1a7d6b30 py-3px rounded-4px size-fit select-none">
                      <p class="text-(10px #1a7d6b)">管理员</p>
                    </div>
                  </n-flex>
                </ContextMenu>
              </template>
              <!-- 用户个人信息框 -->
              <InfoPopover v-if="selectKey === item.userID" :uid="item.userID" :activeStatus="item.isOnline" />
            </n-popover>
          </template>
        </n-virtual-list>
      </n-flex>
    </n-flex>
  </div>
</template>
<script setup lang="ts">
import { useCommon } from '@/hooks/useCommon.ts'
import { useWindow } from '@/hooks/useWindow'
import { useImageViewer } from '@/stores/imageViewer'
import { useTencentGroupStore } from '@/stores/tencentGroupStore.ts'
import TencentCloudChat, { GroupMember } from '@tencentcloud/chat'
import { useChatMain } from '@/hooks/useChatMain.ts'
import { usePopover } from '@/hooks/usePopover.ts'
import { useDebounceFn } from '@vueuse/core'
import { InputInst } from 'naive-ui'
import { useTencentUserStore } from '@/stores/tencentUserStore.ts'
import { useMiaoxinCompanyStore } from '@/stores/miaoxinCompanyStore.ts'

const miaoxinCompanyStore = useMiaoxinCompanyStore()
const tencentGroupStore = useTencentGroupStore()
const tencentUserStore = useTencentUserStore()
const { optionsList, report, selectKey } = useChatMain()
const { openMsgSession } = useCommon()
const { createWebviewWindow } = useWindow()
const IMAGEWIDTH = 630
const IMAGEHEIGHT = 660
const { content } = defineProps<{
  content: any
}>()
const item = ref<any>(null)
const avatar = ref<string>('')
const offset = ref<number>(0)
const infoPopoverRefs = ref<Record<string, any>>([])
const inputInstRef = ref<InputInst | null>(null)
const { handlePopoverUpdate, enableScroll } = usePopover(selectKey, 'image-chat-detail')
provide('popoverControls', { enableScroll })
/** 是否是搜索模式 */
const isSearch = ref(false)
const searchRef = ref('')
const groupMemberList = computed(() => {
  if (content.type === 'group') {
    return Object.values(tencentGroupStore.groupMemberMap[content.uid])
  }
})
const filteredUserList = shallowRef(groupMemberList.value)

// 编辑本群昵称相关状态
const isEditingNickname = ref(false)
const nicknameValue = ref('')
const nicknameInputRef = useTemplateRef('nicknameInputRef')

// 添加一个新的计算属性来合并用户列表
const mergedUserList = computed(() => {
  // 转换回数组并按在线状态排序
  return groupMemberList.value
})

const isOwner = computed(() => content.type === 'group' && content.data.ownerID === tencentUserStore.myProfile.userID)

const getCompanyAndDepartment = (item: GroupMember) => {
  const profile = miaoxinCompanyStore.getOrganizationUserProfileById(item.userID)
  return `${item.nameCard || item.nick} (${profile.CompanyNickName}-${profile.DepartmentName})`
}

watch(
  () => content,
  (val) => {
    if (val.type === 'company') {
      item.value = val.data
      avatar.value = item.value.Avatar
    }

    if (val.type === 'group') {
      offset.value = 0
      item.value = tencentGroupStore.groupList.find((group) => group.groupID === val.uid)
      avatar.value = item.value.avatar
    }
  },
  {
    immediate: true
  }
)

const quitGroup = async () => {
  await tencentGroupStore.quitGroup(item.value.groupID)
}

const dismissGroup = async () => {
  await tencentGroupStore.dismissGroup(item.value.groupID)
}

/**
 * 切换搜索模式并自动聚焦输入框
 */
const handleSelect = () => {
  isSearch.value = !isSearch.value
  nextTick(() => {
    inputInstRef.value?.select()
  })
}

/**
 * 处理滚动事件
 * @param event 滚动事件
 */
const handleScroll = (event: Event) => {
  const target = event.target as HTMLElement
  const isBottom = target.scrollHeight - target.scrollTop === target.clientHeight

  if (isBottom) {
    tencentGroupStore.getGroupMemberList(item.value.groupID)
  }
}

// 修改watch监听器
watch(
  () => groupMemberList,
  (newVal) => {
    // 如果正在搜索，则应用搜索过滤
    if (searchRef.value) {
      filteredUserList.value = mergedUserList.value?.filter((user) => {
        user?.nameCard?.toLowerCase().includes(searchRef.value.toLowerCase()) ||
          user?.nick?.toLowerCase().includes(searchRef.value.toLowerCase())
      })
    } else {
      filteredUserList.value = groupMemberList.value
    }

    console.log('监听群聊用户列表', groupMemberList, newVal)
  },
  {
    immediate: true,
    deep: true
  }
)

/**
 * 监听搜索输入过滤用户
 * @param value 输入值
 */
const handleSearch = useDebounceFn((value: string) => {
  if (!value) {
    // 如果搜索框为空，只显示在线用户列表
    filteredUserList.value = groupMemberList.value
    return
  }

  // 从合并后的用户列表中搜索
  filteredUserList.value = mergedUserList.value?.filter(
    (user) =>
      user?.nameCard?.toLowerCase().includes(value.toLowerCase()) ||
      user?.nick?.toLowerCase().includes(value.toLowerCase())
  )
}, 10)

/**
 * 重置搜索状态
 */
const handleBlur = () => {
  if (searchRef.value) return
  isSearch.value = false
  searchRef.value = ''
  // 重置为只显示在线用户列表
  filteredUserList.value = groupMemberList.value
}

// 复制
const handleCopy = (account: string) => {
  if (account) {
    navigator.clipboard.writeText(account)
    window.$message.success(`复制成功 ${account}`)
  }
}

const footerOptions = ref<OPT.Details[]>([
  {
    url: 'message',
    title: '发信息',
    click: (type) => {
      let info: any = item.value
      if (content.type === 'company') {
        info = {
          userID: item.value.UserId
        }
      }

      openMsgSession(info, type)
    }
  }
  // {
  //   url: 'phone-telephone',
  //   title: '打电话',
  //   click: () => {
  //     console.log('完善中...')
  //   }
  // },
  // {
  //   url: 'video-one',
  //   title: '打视频',
  //   click: () => {
  //     console.log('完善中...')
  //   }
  // }
])

// 开始编辑本群昵称
const startEditNickname = () => {
  nicknameValue.value = item.value.selfInfo.nameCard || ''
  isEditingNickname.value = true
  nextTick(() => {
    nicknameInputRef.value?.focus()
  })
}

// 处理本群昵称更新
const handleNicknameUpdate = async () => {
  if (nicknameValue.value !== item.value.myName) {
    item.value.selfInfo.nacard = nicknameValue.value
    window.$message.success('本群昵称更新成功')
  }
  isEditingNickname.value = false
}

// 打开图片查看器
const openImageViewer = async () => {
  try {
    const imageViewerStore = useImageViewer()
    // 设置为单图模式并传入图片URL
    imageViewerStore.setSingleImage(avatar.value)

    // 创建窗口，使用计算后的尺寸
    await createWebviewWindow('图片查看', 'imageViewer', IMAGEWIDTH, IMAGEHEIGHT, '', true, IMAGEWIDTH, IMAGEHEIGHT)
  } catch (error) {
    console.error('打开图片查看器失败:', error)
  }
}
</script>

<style scoped lang="scss">
@use '@/styles/scss/chat-sidebar';
</style>
